# -*- coding: utf-8 -*-
# @File  : 进程通信.py
# @Author: zbh
# @Date  : 2025/2/19_15:51


import multiprocessing
import time

def producer(queue):
    '''
    生产者
    :param queue:
    :return:
    '''
    for i in range(5):
        queue.put(f"Message {i**2}")
        print(f"Produced: Message {i**2}")
        time.sleep(1)
    queue.put(None)  # 发送结束信号

def consumer(queue):
    '''
    消费者
    :param queue:
    :return:
    '''
    while True:
        item = queue.get()
        if item is None:
            break
        print(f"Consumed: {item}")

if __name__ == "__main__":
    queue = multiprocessing.Queue()

    # 创建生产者和消费者进程
    p1 = multiprocessing.Process(target=producer, args=(queue,))
    p2 = multiprocessing.Process(target=consumer, args=(queue,))

    # 启动进程
    p1.start()
    p2.start()

    # 等待进程结束
    p1.join()
    p2.join()

    print("All processes are done.")






